﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using QBWeb.BLL;
using QBWeb.Models;
using QBWeb.ViewModels;

namespace QBWeb.Controllers
{
    /// <summary>
    /// 试卷模块控制器
    /// </summary>
    public class TestPaperTbsController : Controller
    {
        private readonly QBDbContext db = new QBDbContext();

        /// <summary>
        /// GET: 试卷主页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Index(int?id, string className)
        {
            //return View();
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            //默认保存30分钟 课程id给word导入用
            var userId = User.Identity.GetUserId();
            if (userId == "") userId = "Temp";
            Session[userId] = id;
            Session.Timeout = 2 * 60; //延迟两个小时后清除

            var curriculum = db.Curricula.Find(id);
            if (curriculum == null)
            {
                return HttpNotFound();
            }
            ViewData["classInfo"] = db.ClassesTbs.FirstOrDefault(a => a.CurriculumId == id && a.ClassName == className)?.ClassName;
            return View(curriculum);
        }

        /// <summary>
        /// 选项卡返回页面
        /// </summary>
        /// <param name="cardIndex"></param>
        /// <returns></returns>
        public ActionResult ReturnCard(int cardIndex)
        {

            switch (cardIndex)
            {
                case 0:
                    return PartialView("_Card1");
                case 1:
                    string userId = User.Identity.GetUserId();
                    return PartialView("_Card2",db.QuestionTbs.Where(t=>t.TeacherId == userId).ToList());
                default:
                    return PartialView("_Card5");
            }
        }
        //返回本月创建的试卷
        //public ActionResult Index(int Id, string times)
        //{

        //}


        #region 教师试卷功能
        //返回所有试卷
        /// <summary>
        /// 返回所有教师试卷
        /// </summary>
        /// <param name="curriculaId"></param>
        /// <returns></returns>
        public JsonResult ResultAllTest(int curriculaId)
        {
            var str = new List<object>();
            var testPapers = db.TestPaperTbs.Include(t => t.Issue).Where(a => a.CurriculaId == curriculaId).ToList();
            foreach (var x in testPapers)
            {
                str.Add(new
                {
                    testId = x.Id,
                    testName = x.TestName,
                    author = x.Creator,
                    createTime = x.CreateTime.ToString(),
                    modifyTime = x.ModifyTime.ToString(),
                    status = x.Issue.Status
                });
            }
            return Json(str, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 创建试卷
        /// </summary>
        /// <param name="testName"></param>
        /// <param name="cid"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult CreateTest(string testName,int cid)
        {
            InterfaceBll.CreateTest(testName, User.Identity.Name,cid);
            return Json(new { msg = "创建成功" }) ;
        }
        /// <summary>
        /// 返回发布页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public PartialViewResult PutTestPaper()
        {
            return PartialView("_PutTestPaper");
        }
        /// <summary>
        /// 考试发布
        /// </summary>
        /// <param name="id"></param>
        /// <param name="notes"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="onTime"></param>
        /// <returns></returns>
        public ActionResult PutOut(int id,string notes,int[] classes,DateTime start,DateTime end,int? onTime)
        {
            InterfaceBll.PutOut(id, notes,classes, start, end, onTime);
            return Json(new { msg = "发布成功！" });
        }
        /// <summary>
        /// 结束试卷发布
        /// </summary>
        /// <param name="testPaperTbId"></param>
        /// <returns></returns>
        public JsonResult ShoutDownIssue(int testPaperTbId)
        {
            var test = db.TestPaperTbs.Where(t => t.Id == testPaperTbId);
            if (!test.Any()) throw new Exception("试卷不存在");
            object[] param = { 3, testPaperTbId }; //已结束=3
            const string sql = "Update Issues set status=@P0 where Id=@P1";
            var count = db.Database.ExecuteSqlCommand(sql, param);
            if (count < 1) throw new Exception("保存失败");
            return Json(new { msg = "结束发布成功" });
        }
        /// <summary>
        /// 删除试卷
        /// </summary>
        /// <param name="testPaperTbId"></param>
        /// <returns></returns>
        public JsonResult DeleteTest(int testPaperTbId)
        {
            try
            {
                InterfaceBll.DeleteTest(testPaperTbId);
                return Json(new { msg = "删除成功！" }); ;
            }
            catch (Exception ex)
            {
                return Json(new { msg = ex.Message }); ;
            }
        }
        /// <summary>
        /// 修改试卷
        /// </summary>
        /// <param name="testPaperTbId"></param>
        /// <param name="testName"></param>
        /// <param name="creator"></param>
        /// <returns></returns>
        public JsonResult EditTest(int testPaperTbId, string testName, string creator)
        {
            try
            {
                InterfaceBll.EditTest(testPaperTbId, testName, creator);
                return Json(new { msg = "修改成功！" }); ;
            }
            catch (Exception ex)
            {
                return Json(new { msg = ex.Message }); ;
            }
        }

        #endregion


        /// <summary>
        /// 考试人数情况
        /// </summary>
        /// <param name="testId"></param>
        /// <returns></returns>
        public JsonResult ResultAnswer(int testId)
        {
            var answer = db.AnswerRecordTbs.Where(t => t.TestId == testId).ToList();
            var answerInfo = answer.Count();//统计实际考试人数
            var classId = db.ClassTestPaperTbs.Where(t => t.IssueId == testId).Select(t=>t.ClassesTbId).ToList();
            var classAnswer = classId.Sum(item => db.ClassesStudentTbs.Count(t => t.ClassesTbId == item));//统计应参加考试人数
            var time = db.Issues.First(t => t.Id == testId);//考试时间
            var testTime = 
                new
                {
                    startTime = time.StartTime.ToString(),
                    endTime = time.EndTime.ToString(),
                    onTime = time.OnTime.ToString()
                };
            return Json(new { Answer = answerInfo,student = classAnswer,TestTime = testTime }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 查询班级
        /// </summary>
        /// <param name="curriculumId"></param>
        /// <returns></returns>
        public JsonResult FindClasses(int curriculumId)
        {
            var findRes = db.ClassesTbs.Where(a => a.CurriculumId == curriculumId).Select(b => new { b.ClassName, b.Id });
            var item = new List<object>();
            foreach (var i in findRes)
            {
                item.Add(new
                {
                    className = i.ClassName,
                    classId = i.Id
                });
            }
            return Json(item, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 查询试卷详情
        /// </summary>
        /// <param name="testId"></param>
        /// <returns></returns>
        public JsonResult ResultExamInfo(int testId)
        {
            var stuInfo = db.AnswerInfoTbs.Where(t => t.TestPaperTbId == testId).ToList();
            var stu = db.AnswerRecordTbs.Where(t => t.TestId == testId).Select(t => t.StudentName).ToList();
            var stuScoreList = new List<object>();
            foreach(var item in stu)
            {
                var stuScore = stuInfo.Where(t => t.UserName == item&&t.TF==1).Sum(a=>a.Score); 
                stuScoreList.Add(new { stu = item, score = stuScore });
            }
            return Json(stuScoreList);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="disposing"></param>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
